# 准备合并逻辑。。两个数据库字段统一
from datetime import datetime
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

from django.conf import settings
if settings.DATABASE_TYPE == 'mysql':
    from tanxi.models.mysql.mysql_user_model import UserModel, UserManager 
    from tanxi.models.mysql.mysql_AIProject_model import AIProjectModel
        
elif settings.DATABASE_TYPE == 'sqlite':
    from tanxi.models.sqlite.sqlite_user_model import SqliteUserModel as UserModel
    from tanxi.models.sqlite.sqlite_user_model import SqliteUserManager as UserManager
    # from tanxi.models.sqlite.sqlite_travel_model import SqlitetravelModel as travelModel
else:
    raise ValueError("Unsupported database type specified in settings.")

from tanxi.client.Handler.Logger import log_info
from django.utils import timezone
from django.core.exceptions import ObjectDoesNotExist


from demoPython.settings import db_config
from django.db.models import F

# 创建数据库引擎
engine = create_engine(f'mysql+mysqlconnector://{db_config["user"]}:{db_config["password"]}@{db_config["host"]}/{db_config["database"]}')
Session = sessionmaker(bind=engine)



class AIProjectQueryHandler():
    def __init__(self):
        self.session = Session()

    def query_ai_projects(self, id=None, name=None, type=None, author=None, is_public=None):
        """
        查询AI项目，根据名称、类型、作者和公开状态进行过滤
        """
        projects = AIProjectModel.objects.annotate(
            author_name=F('user__name')
        ).values(
            'id', 'name', 'description', 'type', 'author', 
            'created_at', 'updated_at', 'demo_url', 'cover_image',
            'repo_url', 'status', 'tech_stack', 'is_public', 'author_name'
        )
        
        if id:
            id = int(id)
            log_info(f"AI项目ID {id}")
            projects = projects.filter(id=id)
            
        if name:
            projects = projects.filter(name__icontains=name)
            
        if type:
            projects = projects.filter(type=type)
            
        if author:
            projects = projects.filter(author__icontains=author)
            
        if is_public is not None:
            projects = projects.filter(is_public=is_public)
            
        return projects


class AIProjectUpdateHandler:
    def update_or_create_ai_project(self, project_data):
        """
        更新或创建AI项目
        """
        if not project_data:
            raise ValueError("AI项目数据不能为空")

        project_id = project_data.get('id')

        if project_id:
            try:
                project = AIProjectModel.objects.get(id=project_id)
                log_info(f"更新现有AI项目: ID={project_id}, 数据={project_data}")

                for field, value in project_data.items():
                    if hasattr(project, field) and field != 'id':
                        setattr(project, field, value)
                project.updated_at = timezone.now()
                project.save()
                return {'project_id': project.id, 'message': 'AI项目更新成功'}

            except ObjectDoesNotExist:
                raise ValueError(f"AI项目 ID {project_id} 不存在")
            except Exception as e:
                log_info(f"更新AI项目失败: {e}")
                raise ValueError(f"更新AI项目失败: {str(e)}")

        # 创建新项目
        log_info(f"创建新AI项目: 数据={project_data}")

        defaults = {
            'name': '',
            'description': '',
            'type': 'other',
            'author': '',
            'demo_url': '',
            'cover_image': None,
            'repo_url': '',
            'status': 'active',
            'tech_stack': [],
            'is_public': True,
            'created_at': timezone.now(),
            'updated_at': timezone.now()
        }
        defaults.update(project_data)
        defaults.pop('id', None)

        try:
            project = AIProjectModel.objects.create(**defaults)
            return {'project_id': project.id, 'message': 'AI项目创建成功'}
        except Exception as e:
            log_info(f"创建AI项目失败: {e}")
            raise ValueError(f"创建AI项目失败: {str(e)}")

    def delete_ai_project(self, id):
        """
        删除AI项目
        """
        AIProjectModel.objects.filter(id=id).delete()
        return True